package com.zytech.zspider.task;

import com.zytech.modules.lang.Requires;
import com.zytech.zspider.core.TaskDefinition;
import com.zytech.zspider.core.TaskResult;

import java.util.Arrays;
import java.util.List;

/**
 * @author siuming
 */
public final class TaskResultHandlerPipeline implements TaskResultHandler {

    private final List<TaskResultHandler> handlers;

    /**
     * @param handers
     */
    public TaskResultHandlerPipeline(TaskResultHandler... handers) {
        this(Arrays.asList(handers));
    }

    /**
     * @param handlers
     */
    public TaskResultHandlerPipeline(List<TaskResultHandler> handlers) {
        Requires.notNull(handlers, "handlers must not be null.");
        this.handlers = handlers;
    }

    @Override
    public TaskResult onResult(TaskExecutor executor,
                               TaskDefinition task,
                               TaskContext context,
                               TaskResult result) {

        TaskResult usingResult = result;
        for (TaskResultHandler handler : handlers) {
            usingResult = handler.onResult(executor, task, context, result);
        }
        return usingResult;
    }
}
